<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Member extends MY_Controller {

	function Member()
	{
		parent::MY_Controller();
        $this->load->helper('page');
	}

    function index() {
        self::center();
    }

	/**
	 * 用户注册
	 * @return null
	 */
	function register(){
		page_common();
		if ($this->input->post('action') == 'register'){
			$form = array('realname','password','password2','gender','bank_name','bank_account','bank_account2','mobile','tel_code','tel','qq','email','reg_comment');
			foreach($form as $val){
				$$val = $this->input->post($val);
			}
			if (!$password || !$password2){
				parent::redirect('必须输入密码','back');
			} else {
				if ($password != $password2){
					parent::redirect('两次密码输入不一致！','back');
				}
			}
			if(!$bank_account || !$bank_account2){
				unset($form['bank_account2']);
			} else {
				if ($bank_account != $bank_account2){
					parent::redirect('两次银行账户输入不一致！','back',3);
				}
			}
			$tel = $tel_code . '-' . $tel;
			if (!$mobile && $tel == '-'){
				parent::redirect('手机和电话至少填写一项','back');
			}
			unset($form[array_search('password2',$form)]);
			unset($form[array_search('bank_account2',$form)]);
			unset($form[array_search('tel_code',$form)]);
			//print_r($form);exit;
			$utype = 'CM';
			$this->load->model('Mmember');
			$discount_info = $this->Mmember->get_discount_info($utype);
			$disc_type 	= $discount_info['disc_type'];
			$discount 	= $discount_info['discount'];
			$ids = $this->Mmember->get_valid_member_id(1);
			$id = $ids[0];
			$username = $utype.str_pad($id,6,'0',STR_PAD_LEFT);
			$reg_time = date('Y-m-d H:i:s');
			$reg_ip = $this->input->ip_address();
			$form = array_merge($form,array('utype','username','reg_time','reg_ip','disc_type','discount'));
			foreach($form as $val){
				$values[$val] = $$val;
			}
			if ($this->Mmember->insert_new_user($values)){
				$this->Mmember->update_member_id_state($id);
                $info = $this->Mmember->get_user_info('username',$username);
			    parent::set_session_value('user',array('uid'=>$info['uid'],'username'=>$username,'realname'=>$info['realname']));
				parent::message('恭喜你注册成功！<br />请牢记您的用户名：'.$username,base_url().'member/center','点击此处，系统将为您自动登录。');
			} else {
				parent::redirect('注册失败，请返回重试！','back',3);
			}
			exit();
		}
		$this->template->view('v1/register');
	}

	/**
	 * 用户登录
	 * @return null
	 */
	function login(){
		$form = array('username','password');
		foreach($form as $val){
			$$val = $this->input->post($val);
		}
		$this->load->model('Mmember');
		$flag = $this->Mmember->check_user_valid($username,$password);
		if ($flag == 99){
			$info = $this->Mmember->get_user_info('username',$username);
			parent::set_session_value('user',array('uid'=>$info['uid'],'username'=>$username,'realname'=>$info['realname']));
			$info['login_sum']++;
            $update = array('login_ip'=>$this->input->ip_address(),'login_time'=>date('Y-m-d H:i:s'),'login_sum'=>$info['login_sum']);
            $this->Mmember->update_member_data($info['uid'],$update);
			parent::redirect('登录成功！马上转到会员中心',base_url().'member/center',3);
		} elseif ($flag == 2) {
			parent::redirect('密码错误，请重试！',base_url(),3);
			//echo 'invalid password';
		} elseif ($flag == 1) {
			parent::redirect('此用户不存在，请检查后重试！',base_url(),3);
			//echo 'invalid username';
		} else {
			parent::redirect('未知错误，请重试！',base_url(),3);
			//echo 'unknown error';
		}
	}

	/**
	 * 用户退出
	 * @return null
	 */
	function logout(){
		parent::unset_session_value('user');
		parent::redirect('注销成功！',base_url());
	}

    /**
     * 帐户中心
     */
    function center(){
        $user = parent::get_session_value('user');
        if(!$user){
            parent::redirect('你还未登录，请先登录', base_url(), 3);
        }
        //page_common();
        //$this->template->view('v1/member');
        redirect(base_url().'order/my/');
    }

    function forgot(){
        page_common();
    	$this->template->view('v1/password_forgot');
    }

    /**
     * 密码找回
     * @return unknown_type
     */
    function pwd_back(){
    	$user 	= $this->input->post('user');
    	$email 	= $this->input->post('email');
    	if(!$user || !$email){
    		parent::redirect('你有必填项目没有填写！','back');
    	}
    	$this->load->model('Mmember');
    	$res = $this->Mmember->get_pwd_back($user,$email);
    	if($res === '1'){
    		parent::redirect('此用户不存在，请返回检查后重新提交','back');
    	} elseif($res === '2'){
    		parent::redirect('注册邮箱填写不正确。','back');
    	} else {
    		self::send_mail($email,$res);
    	}
    }

    /**
     * 发送密码邮件
     * @param $email
     * @param $pwd
     * @return unknown_type
     */
    function send_mail($email,$res){
    	$this->load->library('email');
		$email_from = $this->config->item('email_from');
		$from_name  = $this->config->item('from_name');
		$config = $this->config->item('email_config');
		$this->email->initialize($config);
		$this->email->from($email_from, $from_name);
		$this->email->to($email);
		//$this->email->cc('another@another-example.com');
		//$this->email->bcc('them@their-example.com');
		list($realname,$username,$pwd) = explode('|||',$res);
		$subject = '谋成网络服务密码找回邮件';
		$this->template->assign_array(array('realname'=>$realname,'username'=>$username,'pwd'=>$pwd));
		$message = $this->template->fetch('v1/pwd_email.tpl');
		$this->email->subject($subject);
		$this->email->message($message);
		if($this->email->send()){
            log_common('email','member.php','send_mail','email succ',array('username'=>$username,'password'=>$pwd,'email'=>$email));
            parent::redirect('密码已经发送到你的注册邮箱，请登录邮箱获取密码。', base_url());
        } else {
            log_common('email','member.php','send_mail','email fail',array('debugger'=>$this->email->print_debugger()));
            parent::redirect('邮件发送失败，请重试！', 'back');
        }
    }

    function modify(){
        $session = parent::get_session_value('user');
        if(!$session){
            parent::redirect('你还未登录，请先登录', base_url(), 3);
        }
        if($this->input->post('action') == 'modify'){
            $post = array('realname','mobile','tel_code','tel','qq','msn');
            $data = $this->input->get_data($post);
            $data['tel'] = $data['tel_code'].'-'.$data['tel'];
            unset($data['tel_code']);
            $uid = $this->input->post('uid');
            $this->load->model('Mmember');
            if($this->Mmember->update_member_data($uid,$data)){
                parent::redirect('信息修改成功！', base_url().'member/center/');
            } else {
                parent::redirect('信息修改失败，请返回重试！', 'back');
            }
        }
        $this->load->model('Mmember');
        $user = $this->Mmember->get_user_info('uid',$session['uid']);
        //print_r($user);exit;
        if(strpos($user['tel'],'-')){
        	list($tel_code,$tel) = explode('-',$user['tel']);
        } else {
        	$tel_code = '';
        	$tel = $user['tel'];
        }
        $user['tel_code'] = $tel_code;
        $user['tel']      = $tel;
        page_common();
        $this->template->view('v1/member_modify',array('user'=>$user));
    }

    function send_confirm(){
    	$session = parent::get_session_value('user');
        if(!$session){
            parent::redirect('你还未登录，请先登录', base_url(), 3);
        }
        $this->load->model('Mmember');
        $user = $this->Mmember->get_user_info('uid',$session['uid']);
    	$this->load->library('email');
		$email_from = $this->config->item('email_from');
		$from_name  = $this->config->item('from_name');
		$config = $this->config->item('email_config');
		$this->email->initialize($config);
		$this->email->from($email_from, $from_name);
		$this->email->to($user['email']);
		$this->load->library('encrypt');
		$str = $user['username'].'|||'.time();
		$key = $this->encrypt->encode($str);
		$subject = '谋成网络服务确认邮件';
		$this->template->assign_array(array('realname'=>$user['realname'],'key'=>$key));
		$message = $this->template->fetch('v1/email_confirm.tpl');
		$this->email->subject($subject);
		$this->email->message($message);
		//$this->email->send();
		//echo $this->email->print_debugger();exit;
		if($this->email->send()){
            log_common('email','member.php','send_confirm','email succ',array('realname'=>$user['realname'],'key'=>$key));
            parent::redirect('确认邮件已经发送到你的邮箱，请点击邮件中的确认链接继续', base_url());
        } else {
            log_common('email','member.php','send_confirm','email fail',array('debugger'=>$this->email->print_debugger()));
            parent::redirect('邮件发送失败，请重试！', 'back');
        }
    }

    function modify_continue($key=''){
    	if($key == ''){
    		log_common('member','member.php','modify_submit','key is null');
    		parent::redirect('链接不正确或已经过期，请确认后继续。',base_url());
    	}
    	$this->load->library('encrypt');
		$str = $this->encrypt->decode($key);
		list($username,$timestamp) = explode('|||',$str);
		$now = time();
		$empire = $this->config->item('confirm_empire') ? $this->config->item('confirm_empire') : 10;
		if($now - $timestamp > $empire*60){
			log_common('member','member.php','modify_submit','empire is gone',array('now'=>$now,'timestamp'=>$timestamp,'empire'=>$empire));
    		parent::redirect('该链接已经过期，请再次发送确认邮件！。',base_url());
		}
		$this->load->model('Mmember');
        $user = $this->Mmember->get_user_info('username',$username);
        if(!$user){
        	log_common('member','member.php','modify_submit','user'.$username.' not exist');
        	parent::redirect('此用户不存在，请确认或联系网站客服人员',base_url());
        }
        page_common();
        $this->template->view('v1/modify_continue.tpl',array('user'=>$user));
    }

    function modify_submit(){
    	$username = $this->input->post('username');
    	if(!$username){
    		log_common('member','member.php','modify_submit','user'.$username.' is null');
    		parent::redirect('不存在用户信息',base_url());
    	}
    	$this->load->model('Mmember');
        $user = $this->Mmember->get_user_info('username',$username);
    	if(!$user){
    		log_common('member','member.php','modify_submit','user'.$username.' not exist');
        	parent::redirect('此用户不存在，请确认或联系网站客服人员','back');
        }
        $form = array('bank_name','bank_account','email');
        $data = $this->input->get_data($form);
    	if($this->Mmember->update_member_data($user['uid'],$data)){
    		log_common('member','member.php','modify_submit','user'.$username.' modify success',$data);
       		parent::redirect('信息修改成功！', base_url());
        } else {
        	log_common('member','member.php','modify_submit','user'.$username.' modify fail');
            parent::redirect('信息修改失败，请返回重试！', 'back');
        }
    }

    function password(){
        $user = parent::get_session_value('user');
        if(!$user){
            parent::redirect('你还未登录，请先登录', base_url(), 3);
        }
        if($this->input->post('action') == 'modify'){
            $post = array('old','new','new2');
            $data = $this->input->get_data($post);
            if(!$data['old'] || !$data['new'] || !$data['new2']){
                parent::redirect('你有必填项目没有填写，请返回重新填写！', 'back');
            }
            $this->load->model('Mmember');
            $flag = $this->Mmember->check_user_valid($user['username'],$data['old']);
            if($flag == 2){
                parent::redirect('原密码输入不正确，请返回重新输入！', 'back');
            } elseif ($flag == 99){
                if($data['new'] != $data['new2']){
                    parent::redirect('两次新密码输入不一致！', 'back');
                } else {
                    $values = array('password'=>$data['new']);
                    if($this->Mmember->update_member_data($user['uid'],$values)){
                        parent::redirect('密码修改成功！', base_url().'member/center/');
                    } else {
                        parent::redirect('密码修改失败，请返回重试！', 'back');
                    }
                }
            } else {
                parent::redirect('发生未知错误，请联系技术人员！', 'back');
            }
        }
        page_common();
        $this->template->view('v1/member_password');
    }



}

?>